<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品列表</title>
<link href="/resources/lib/ligerUI/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" />
<link href="/resources/lib/ligerUI/skins/ligerui-icons.css" rel="stylesheet" type="text/css" />

<link href="/resources/lib/jquery_plug/plupload-2.1.2/js/jquery.ui.plupload/css/jquery.ui.plupload.css" type="text/css" rel="stylesheet" media="screen">
<link href="/resources/lib/jquery_plug/jquery-ui/themes/cupertino/jquery-ui.min.css" rel="stylesheet" type="text/css" />
 
<!-- <script src="/resources/lib/jquery/jquery-1.3.2.min.js" type="text/javascript"></script> -->
<script src="/resources/lib/jquery/jquery-1.11.1.min.js" type="text/javascript"></script>

<script src="/resources/lib/jquery_plug/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
<script src="/resources/lib/jquery_plug/layer-v1.8.5/layer/layer.min.js" type="text/javascript"></script>
<script src="/resources/lib/jquery_plug/plupload-2.1.2/js/plupload.full.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/resources/lib/jquery_plug/plupload-2.1.2/js/i18n/zh_CN.js" charset="UTF-8"></script>
<script src="/resources/lib/jquery_plug/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.min.js" type="text/javascript"></script>

 
<script src="/resources/lib/ligerUI/js/ligerui.all.js" type="text/javascript"></script>
<script src="/resources/lib/ligerUI/js/ex/ligerGrid.showFilter.js" type="text/javascript"></script>
<script src="/resources/lib/ligerUI/js/ex/ligerFilterEx.js" type="text/javascript"></script>
<script src="/resources/js/jsF7.js" type="text/javascript"></script>
<script src="/resources/js/selectData.js" type="text/javascript"></script>
<script type="text/javascript">
    var bool_data = [
                     { id: '1', value: '1', text: '是' },
                     { id: '0', value: '0', text: '否' }
                 ];
        var $grid;
        var form;
        var manager;
        $(function (){

       	 $("#layout_tree_grid").ligerLayout({
       		    leftWidth: 200,
               centerBottomHeight:180,
                height: '100%'
       		//onHeightChanged: f_heightChanged 
               
               
            });
        	 var menu = $.ligerMenu({ width: 120, items:
        	        [	
        	         	{ text: '添加新节点', click: addTreeItem, icon: 'add' },
        	         	{ text: '更新选择节点', click: updateTreeItem, icon: 'edit' },
        	            { text: '删除选择节点', click: delTreeItem, icon: 'delete' } 
        	        ]
        	        });
        		//树形
        		manager = $("#tree1").ligerTree({
        			 url:"/categories/categoriesList",
        			 checkbox: false,
        			 isExpand: 2,
        	         idFieldName :'uuid',
        	         slide:false,
        	         parentIDFieldName:'parentId',
        	         textFieldName:'name',
        	         nodeWidth : 300,
        	         isLeaf:function(data){
        	        	 if(data.children){
        	        		 data.leaf = false;
        	        		 return false;
        	        	 }else{
        	        		 data.leaf = true;
        	        		 return true;
        	        	 }
        	         },
        	         onClick:onClick,
        	         onContextmenu: function (node, e){
        	             menu.show({ top: e.pageY, left: e.pageX });
        	             return false;
        	         }
        	     });
        	
        	 
        	//创建查询对象
        	/* form = $("#form2").ligerForm({
            	  inputWidth: 150, labelWidth: 80, space: 40,
                  fields: [ 
                      { label: "商品名", name: "userName",  width: 100, type: "text", validate: {minlength: 5 } },
                      { label: "是否可用", name: "status",  width: 100, type: "select",editor: {data:bool_data}}
                  ]
            });  */
            //创建表格对象 高级查询editor 识别编辑器有：combobox date number string
            $grid = $("#maingrid").ligerGrid({
                columns: [
                { name: 'uuid', hide:true,type:"text"},
                { display: '编码', name: 'number', minWidth: 140,type:"text"},
                { display: '名称', name: 'name', minWidth: 140,type:"text"},
                { display: '商品条码', name: 'barCode', minWidth: 140,type:"text"},
                { display: '规格型号', name: 'standard', minWidth: 100,type:"text"},
               { display: "商品分类", name: "matCategory.uuid", NotFilter:true,  minWidth: 100, type: "popup",textField:"matCategory.name",
             	   editor: {
             		  		type: "popup",
	                       grid: getCategoriesGrid(true),
	                       valueField:'uuid',
	                       textField: 'name',
	                       parms :{date:new Date().getTime()},
	                       realTimeLoad:true
	              	 }
                },
                { display: "基本计量单位", name: "baseUnit.uuid",  minWidth: 140, type: "popup",textField:"baseUnit.name",
             	   editor: {
             		  		type: "popup",
	                       grid: getBaseUnitMeasureGrid(true),
	                       valueField:'uuid',
	                       textField: 'name',
	                       parms :{date:new Date().getTime()},
	                       realTimeLoad:true
	              	 }   
                },
                { display: "安全库存", name: "safeStock",  minWidth: 100, type: "spinner",editor:{type: 'int',isNegative:false}},
                { display: "最小采购量", name: "minPurchaseAmount",  minWidth: 100, type: "spinner",editor:{type: 'int',isNegative:false}},
                { display: "商品图片", name: "matPicture",  minWidth: 100, type: "text"},
                
                /* 
                { display: "组合商品", name: "isGroupM",  minWidth: 100,type: "select",
                	render:function(item){
                		return getCombobxTextByValue(bool_data,item.isGroupM);
                	},
                	editor: {type:'combobox',options:{data:bool_data,cancelable:false,initValue:"0"}}},
                */
                { display: "批次管理", name: "lotManage",  minWidth: 100,type: "combobox", data:bool_data,textField:"lotManage",
                	render:function(item){
                		try{
                		    return getTrueFlaseText(bool_data,item.lotManage);
                			}catch(e){
                			return null;
                		}
                	},editor: {type:'combobox',options:{data:bool_data,cancelable:false,initValue:"0"}}},
                { display: "条码管理", name: "barCodeManage",  minWidth: 100,  type: "select",
                		render:function(item){
                			try{
                    			return getTrueFlaseText(bool_data,item.barCodeManage);
                			}catch(e){
                				return null;
                			}
                    	},editor: {type:'combobox',options:{data:bool_data,cancelable:false,initValue:"0"}}},
                { display: "序列号管理", name: "sequeManage",  minWidth: 100,  type: "select",
                    		render:function(item){
                    			try{
	                        		return getTrueFlaseText(bool_data,item.sequeManage);
                    			}catch(e){
                    				return null;
                    			}
                        	},editor: {type:'combobox',options:{data:bool_data,cancelable:false,initValue:"0"}}}, 
				{ display: "保质期管理", name: "expiraDateManage",  minWidth: 100,  type: "select",
                        		render:function(item){
                        			try{
	                            		return getTrueFlaseText(bool_data,item.expiraDateManage);
                        			}catch(e){
                        				return null;
                        			}
                            	},editor: {type:'combobox',options:{data:bool_data,cancelable:false,initValue:"0",valueField:"value"
				}}},
				{ display: "保质期", name: "expiraData",  minWidth: 100, type: "spinner",editor:{type:'float',isNegative:false}},
				{ display: "保质期单位", name: "expiraDataUtil", textField:"expiraDataUtil", minWidth: 100,  type: "select",render:function(item){
        			try{
                		return getCombobxTextByValue(shelf_life_unit,item.expiraDataUtil);
        			}catch(e){
        				return null;
        			}
            	},editor: {type:'combobox',options:{data:shelf_life_unit,
					valueField: 'value',textField: 'text'}
				}},
				{ display: "创建人", name: "createUser.uuid", type: 'popup',minWidth:100,textField: 'createUser.trueName',
	            	 editor: {type: "popup",
	                     grid: getSysUserGrid(true),
	                     valueField:'uuid',
	                     textField: 'trueName',
	                     parms :{date:new Date().getTime()},
	                     realTimeLoad:true
	            	 }
	            },
	            { display: "创建日期", name: "createDate", minWidth:100, type: "date",editor:{type:'date'}}
                ],
                autoFilter:true,
                width: '100%', pageSizeOptions: [5, 10, 15, 20], height: '100%',pageSize:20,
                checkbox: true,headerRowHeight:22, rowHeight:22, rownumbers:true,
                url:'/material/listData',
                onLoadData:onloadData,
                onDblClickRow:onDblClickRow,
                toolbar: { items: [
                                   { text: '新增', click: addClick, icon: 'add' },
                                   { line: true },
                                   { text: '修改', click: alertClick, icon: 'modify' },
                                   { line: true },
                                   { text: '删除', click: delClick, icon: 'delete' },
                                   { line: true },
                                   { text: '导入', click: importClick, icon: 'bluebook' },
                                   { line: true },
                                   { text: '导出', click: exportClick, icon: 'down' }
                                   ]
                                   }
            });
            
            $grid = $("#maingrid").ligerGetGridManager();

        });
        //添加
        function addClick(item){ 
        	var node = manager.getSelected();
        	if(node &&node.data && node.data.uuid){
        		f_addTab('addMaterial','新增商品',"/material/addMaterial?matCategoryUuid="+node.data.uuid+"");
        	}else{
        		f_addTab('addMaterial','新增商品',"/material/addMaterial");
        	}
        	
        }
        //双击事件(查看)
        function onDblClickRow(data, rowindex, rowobj){
        	f_addTab('viewMaterial','查看商品','/material/viewMaterial?uuid='+data.uuid);

        }
        
        function importClick(item){
        	var pageii = $.layer({
        	    type: 1,
        	    title: false,
        	    area: ['600', '300'],
        	    border: [0], //去掉默认边框
        	    //shade: [0], //去掉遮罩
        	    closeBtn: [0, true], //去掉默认关闭按钮
        	   // shift: 'left', //从左动画弹出
        	    page: {
        	        html: "<div id='uploader' ></div>"
        	    }
        	});
        	var loadi = null;
        	  $("#uploader").plupload({
        	        // General settings
        	        runtimes : 'html5,flash,silverlight,html4',
        	        url : "/material/importMterialExcel",
        	 
        	        // Maximum file size
        	        max_file_size : '50mb',
        	        multi_selection :false,
        	 
        	        chunk_size: '1mb',
        	 
        	        // Resize images on clientside if we can
        	         resize : {
        	            width : 500,
        	            height : 300,
        	            quality : 90,
        	            crop: true // crop to exact dimensions
        	        },
        	 
        	        // Specify what files to browse for
        	        filters : [
        	                   {title : "Excel files", extensions : "xls,xlsx"}
        	            /* {title : "Image files", extensions : "jpg,gif,png"},
        	            {title : "Zip files", extensions : "zip,avi"} */
        	        ],
        	        // Rename files by clicking on their titles
        	        rename: true,
        	         
        	        // Sort files
        	        sortable: true,
        	 
        	        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        	        dragdrop: true,
        	 
        	        // Views to activate
        	        views: {
        	            list: true,
        	            thumbs: true, // Show thumbs
        	            active: 'thumbs'
        	        },
        	        init:{
        	        	FilesAdded: function(up, files) {
        	        		$.each(up.files, function (i, file) {
        	  	                if (up.files.length <= 1) {
        	  	                    return;
        	  	                }
        	  	                up.removeFile(file);
        	  	            });
        	            },
        	            FileUploaded: function(up, file, info) {
        	            	var re = JSON.parse(info.response);
        	            	if(re && re.code=='SUCCESS'){
        	            		$('#uploader').plupload('notify', 'info', re.message);
        	            	}else{
        	            		$('#uploader').plupload('notify', 'error', re.message);
        	            	}
        	            	if(loadi){
        	            		layer.close(loadi);
        	            	}
        	                console.log(info);
        	            },
        	            BeforeUpload: function(up, file) {
        	                // Called right before the upload for a given file starts, can be used to cancel it if required
        	            	loadi =layer.load('数据处理中…');
        	            },
        	        },
        	 
        	        // Flash settings
        	        flash_swf_url : '/resources/lib/jquery_plug/plupload-2.1.2/js/Moxie.swf',
        	     
        	        // Silverlight settings
        	        silverlight_xap_url : '/resources/lib/jquery_plug/plupload-2.1.2/js/Moxie.xap'
        	    }); 
        	/*   var uploader = $("#uploader").pluploadQueue();

        	  uploader.bind('FilesAdded', function(up, files) {   
        		  $.each(up.files, function (i, file) {
  	                if (up.files.length <= 1) {
  	                    return;
  	                }
  	                up.removeFile(file);
  	            });
        	    up.refresh(); // Reposition Flash/Silverlight   
        	   });    */
        	 //openNewWindow('导入Excel:',400,450,"/material/toExcelImport",{url:'/material/importMterialExcel'});
        }
        
		function exportClick(item){
			var pm='';
			var where = '';
			var rigidCondition = '';
			if($grid.options.parms){
				if($grid.options.parms.length>0){
					pm = JSON.stringify($grid.options.parms);
				}
				if($grid.options.parms.where){
					where = $grid.options.parms.where;
				}
				if($grid.options.parms.rigidCondition){
					rigidCondition = $grid.options.parms.rigidCondition;
				}
			}
			//window.open("/material/exportExcel?pm="+pm+"&where="+where+"&rigidCondition="+rigidCondition, '_blank');
			window.location.href="/material/exportExcel?pm="+pm+"&where="+where+"&rigidCondition="+rigidCondition/* +JSON.stringify($grid.options.parms )*/;
        }
        
        //删除
        function delClick(){
        	var rows = $grid.getSelectedRows();
        	if(rows == null || rows.length < 1){
        		$.ligerDialog.error("请至少选择一行数据");
        		return;
        	}
    		$.ajax({ 
    			url: '/material/delMaterial', 
    			data:{rows : JSON.stringify(rows)}, 
    			type: "post", 
    			dataType:'json',
    			cache : false, 
    			success: function(data){
    				$.ligerDialog.success(data.message,'信息',function(){
    		        	 $grid.reload();
    				});
    			},
    	        error: function (message) {
    	            $.ligerDialog.error("删除失败");
    	        }
    	});
        }
        //修改
        function alertClick(){
        	var rows = $grid.getSelectedRows();
        	if(rows == null || rows.length < 1 || rows.length != 1){
        		$.ligerDialog.error("请选择一条要修改的数据");
        		return;
        	}
        	f_addTab('alterMaterial','修改商品','/material/alterMaterial?uuid='+rows[0].uuid);
        }
        
        //查询
        function viewClick(){
        	//重新加载grid
        	 $grid.reload();
        }
        
      //获取数据前添加过滤条件
      function onloadData(){
    	/*   var cond = JSON.stringify(form.getData());
    	  this.options.parms.cond= cond;
    	  this.options.parms.temp= true; */
    	/*   applay(this.options.parms, [{ name: "cond", value: cond, temp: true }]); */
    	 //this.set('parms', [{ name: "cond", value: cond, temp: true }]);
      }
  	  //添加窗口
      function f_addTab(tabid,text, url){
  		this.parent.f_addTab(tabid,text, url);
      } 
  	  
  	  
  	  function updateTreeItem(){
  		 var node = manager.getSelected();
  		 if(!node){
  			alert("请先选择节点");
         	return;
  		 }
         if( node.data.uuid == ''){
         	alert("请先保存节点");
         	return;
         }else{
       	  openNewWindow('修改商品分类:',400,450,"/categories/addCategories?uuid="+node.data.uuid+"",node,'UPDATE');
         }
  	  }
      //添加节点
      function addTreeItem(){
          var node = manager.getSelected();
         /*  if( node.data.uuid == ''){
          	alert("请先保存节点");
          	return;
          }else{ */
          openNewWindow('新增商品分类:',400,450,'/categories/addCategories',node,'NEW');
          //}
          /* $.ajax({ 
      		url: '/categories/addCategories', 
      		data:{},
      		type: "post",
      		dataType:'json',
      		cache : false, 
      		success: function(obj){
      			var sn = '0000';
      			if(obj){
      				sn = obj.sn;
      			}
      		    var nodes = [];
      		    nodes.push({number:sn, name: $("#txtNode").val(),parentId: node.data.uuid,level:node.data.level+1});
      		    if (node)
      		        manager.append(node.target, nodes); 
      		    else
      		        manager.append(null, nodes);
      		},
              error: function (message) {
              	$.ligerDialog.error('保存失败');
              }
      		}); */
       }
       
       //删除节点
       function delTreeItem(){
      	 var node = manager.getSelected();
      	 if(node.data.parentId == '' || node.data.parentId == null){
      		 $.ligerDialog.question('根节点不能删除');
      		 return;
      	 }
      	 $.ligerDialog.confirm('你确定是要删除数据', function (yes) {		 
      		 if(yes){
      			 if( node.data.children == null){
      				 $.ajax({ 
      						url: '/categories/delCategories', 
      						data:{uuid : node.data.uuid}, 
      						type: "post",
      		     		   	dataType:'json',
      						cache : false, 
      						success: function(obj){
      							if(obj.code=='SUCCESS'){
      								$.ligerDialog.success(obj.message);
          		                    manager.clear();
          		                    manager.setData(obj.data);
          		                    manager.remove(node.target);
      	                    	}else{
      	                    		 $.ligerDialog.error(json.message,"系统提示");
      	                    	}
      						},
      		                error: function (message) {
      		                	$.ligerDialog.error('删除失败');
      		                }
      			 		});
      			      
      			 }else{
      				 $.ligerDialog.question('请先删除子菜单');
      			 }
      		 }
      	 });
       }
       
       //点击事件
       function onClick(note){
    	if(note.data.parentId){
    		if($grid.options.parms){
    			$grid.options.parms.rigidCondition = "matCategory.uuid='"+note.data.uuid+"'";
    		}else{
    			$grid.set('parms', {rigidCondition:"matCategory.uuid='"+note.data.uuid+"'"});
    		}
    	}else{
    		if($grid.options.parms){
    			delete $grid.options.parms.rigidCondition;
    		}
    	}
    	$grid.loadData();
      	 //clearForm();
          // form.setData(note.data);
           /* if(note.data.parentId == '' || note.data.parentId == null){
          	 form.setEnabled(["number"],false);
       	 }else{
       		 form.setEnabled(["number"],true);
       	 } */
       }

       function f_heightChanged(options)
       {
           if ($grid)
        	   $grid.addHeight(options.diff);
           if (manager && options.middleHeight - 24 > 0)
        	   manager.setHeight(options.middleHeight - 24);
       }
       
       
       function openNewWindow(title,height,width,url,data,action_type){
    	   console.log(data);
       	$.ligerDialog.open({
   			height:height,
               width: width,
               title : title,
               url: url, 
               showMax: false,
               showToggle: true,
               showMin: false,
               isResize: true,
               slide: false,
               data:data,
               action_type:action_type
           });
       }
       
       function reloadTree(){
    	   manager.reload();
       }
       
       function appendOrUpdateNode(status,target,node){
     	  var nodes = [];
 		    nodes.push(node);
     	  if(status=='0'){
     		  manager.append(target, nodes);
     	  }else if(status=='2'){
     		  manager.update(target,node);
     	  }
       }
  
       
    </script>
    <style type="text/css"> 
            	#element_to_pop_up { display:none; }
     </style> 
</head>
<body  style="padding:10px">
    <div id="layout_tree_grid">
            <div position="left" title="商品分类">
            	<div class="tree" style="height:100%; overflow: scroll;"> 
		            <ul id="tree1"></ul> 
		        </div> 
            </div>
            <div position="center" title="商品列表" style="height:100%;">
               <div id="maingrid"></div> 
            </div>  
     </div>
   <div style="display:none;">
</body>
</html>
